package com.qipay.admin.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.SocketTimeoutException;


/**
 * @类名称:HttpClientTools.java
 * @时间:2017年12月25日上午11:00:28
 * @版权:公司 Copyright (c) 2017
 */
public class HttpClientTools {

//    // 设置连接超时时间，单位毫秒
    private static int connectTimeout = 10000;
//
//    // 设置从connectManager获取Connection超时时间，单位毫秒
    private static int connectionRequestTimeout = 10000;
//
//    // 请求获取数据的超时时间，单位毫秒
    private static int setSocketTimeout = 10000;
//
    private static ConnectionKeepAliveStrategy myStrategy = null;
    static {
        myStrategy = new ConnectionKeepAliveStrategy() {
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator("Keep-Alive"));
                while (it.hasNext()) {
                    HeaderElement he = it.nextElement();
                    String param = he.getName();
                    String value = he.getValue();
                    if ((value != null) && (param.equalsIgnoreCase("timeout"))) {
                        return Long.parseLong(value) * 1000L;
                    }
                }
                return connectTimeout;
            }
        };
    }

    private static CloseableHttpClient httpclient = HttpClientBuilder.create().setMaxConnTotal(1000).setMaxConnPerRoute(15)
            .setKeepAliveStrategy(myStrategy).build();
//
//
//
//
//    /**
//     * @描述:http client post请求
//     * @作者:lihai
//     * @时间:2017年6月28日 下午5:07:32
//     */
//    @SuppressWarnings("all")
//    public String httpClientSendPost(String url, JSONObject reqParam, String charset) throws SocketTimeoutException, exception {
//        return baseHttpSendPost(url, reqParam.toString(), "UTF-8");
//    }
    /**
     * @描述:铂富通基础网络请求类（推荐二次封装使用）
     * @作者:lihai
     * @时间:2017年9月11日 下午3:43:40
     */
    public static String baseHttpSendPost(String url, String reqParam, String charset) throws SocketTimeoutException, Exception {
        CloseableHttpResponse response = null;
        HttpPost httpPost = null;
        String respContent = null;
        try {
            httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)
                    .setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(Integer.valueOf(setSocketTimeout)).build();
            httpPost.setConfig(requestConfig);
            StringEntity postParams = new StringEntity(reqParam, charset);
            postParams.setContentEncoding(charset);
            postParams.setContentType("application/json");
            httpPost.setEntity(postParams);
            response = httpclient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity he = response.getEntity();
                respContent = EntityUtils.toString(he, charset);
            } else {
                throw new SocketTimeoutException("铂富通基础网络链接非200异常{}" + url);
            }
        } catch (Exception e) {
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (Exception e) {
                }
            }
            if (httpPost != null) {
                try {
                    httpPost.releaseConnection();
                } catch (Exception e) {
                }
            }
        }
        return respContent;
    }

}
